package 链表;

public class 回文链表 {

    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }
        ListNode fast = head;
        ListNode slow = head;
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        //反转后半部分链表
        ListNode pre = null;
        ListNode node = slow.next;
        ListNode next = null;
        while (node.next != null) {
            next = node.next;
            node.next = pre;
            pre = node;
            node = next;
        }
        node.next = pre;
        //    分别比较
        ListNode lastHead = node;

        while (head != null && lastHead != null) {
            if (head.val != lastHead.val) {
                return false;
            }
            head = head.next;
            lastHead = lastHead.next;
        }

        return true;

    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}
